package com.ipet.common.filter;

import com.ipet.utils.JWTUtils2;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class LoginFilter  extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
//        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
//        String requestURI = request.getRequestURI();
//        if(requestURI.contains("login") || requestURI.contains("swagger") || requestURI.contains("api-docs")){
//            return false;
//        }
//        return true;
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        token = JWTUtils2.updateToken(token);
        currentContext.getResponse().addHeader("token" , token);
        return null;
    }
}
